//
//  NewFeatureViewController.swift
//  MicroBlog
//
//  Created by 002 on 15/10/18.
//  Copyright © 2015年 002. All rights reserved.
//

import UIKit

private let WBNewFeatureCellId = "NewFeatureCell"
private let WBNewFeatureImageCount = 4

class NewFeatureViewController: UICollectionViewController {

    //MARK:构造方法
    init() {
        
        // 设置layout的样式
        let layout = UICollectionViewFlowLayout.init()
        layout.itemSize = UIScreen.mainScreen().bounds.size // itemsize等于屏幕大小
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .Horizontal    // 水平滚动
        
        super.init(collectionViewLayout: layout)
        
        collectionView?.bounces = false // 取消弹簧效果
        collectionView?.pagingEnabled = true    // 开启分页
        collectionView?.showsHorizontalScrollIndicator = true   // 水平滚动
        
    }

    // 当前对象和空间初初始化完毕后调用
    override func viewDidAppear(animated: Bool) {
        
        collectionView?.pagingEnabled = true
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 注册CELL
        self.collectionView?.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: WBNewFeatureCellId)
    }
}

//MARK:数据源方法
extension NewFeatureViewController {
    
    //MARK:返回cell
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBNewFeatureCellId, forIndexPath: indexPath) as! NewFeatureCell
        
        cell.imageIndex = indexPath.row
        
        return cell
    }
    
    //MARK:返回cell的个数
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return WBNewFeatureImageCount
    }
    
    //MARK: scrollView停止滚动的方法
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        // 计算当前浏览新特性页面的页数
        let pageIndex = Int(scrollView.contentOffset.x / scrollView.bounds.size.width)
        
        if pageIndex != WBNewFeatureImageCount - 1 {
            return
        }
        
        // 找到最后一页的新特性界面
        let cell = collectionView?.cellForItemAtIndexPath(NSIndexPath.init(forItem: pageIndex, inSection: 0)) as? NewFeatureCell
        // 开启动画
        cell?.startAnima()
    }
    
    // 隐藏标题栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

//MARK:自定义cell
class NewFeatureCell : UICollectionViewCell {
    
    // 图片索引
    var imageIndex : Int = 0 {
        didSet{
            iconView.image = UIImage.init(named: "new_feature_\(imageIndex+1)")
            // 此处也需要设置按钮隐藏
            startButton.hidden = true
        }
    }
    
    // 开始按钮监听方法
    func startBtnClick() {
        print("开始")
        
        // 发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: nil)
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        // 设置UI界面
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:按钮的动画方法
    func startAnima(){
        
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        startButton.userInteractionEnabled = false
        
        // 动画属性
        UIView.animateWithDuration(1.5,     // 动画时长
            delay: 0,                       // 延时时间
            usingSpringWithDamping: 0.6,    // 弹力系数，0-1，越小越弹
            initialSpringVelocity: 10,      // 初始速度，模拟重力加速度
            options: [],                    // 动画选项
            animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
                
            }) { (_) -> Void in
                
                self.startButton.userInteractionEnabled = true
        }
    }
    
    //MARK:UI布局方法
    func setupUI() {
        
        // 1->添加控件
        addSubview(iconView)
        addSubview(startButton)
        
        // 2->布局
        self.iconView.frame = self.bounds
        
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconView.snp_centerX)
            make.centerY.equalTo(iconView.snp_bottom).multipliedBy(0.7)
        }
        
        // 3->设置按钮隐藏（不能单纯在此设置）
        startButton.hidden = true
        
        // 4->添加监听方法
        startButton.addTarget(self, action: "startBtnClick", forControlEvents: .TouchUpInside)
    }
    
    //MARK:懒加载控件
    private lazy var iconView : UIImageView = UIImageView()
    private lazy var startButton : UIButton = UIButton.init(title: "开始体验", color: UIColor.whiteColor(), backImageName: "new_feature_finish_button")
}